# -*- coding: utf-8 -*-
# 数据库操作
from flask_sqlalchemy import SQLAlchemy

from web.flask_web import app

app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:root@127.0.0.1:33006/flasky'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
db = SQLAlchemy(app)


class User(db.Model):
    __tablename__ = 'user'

    id = db.Column(db.Integer, primary_key=True, name='id', autoincrement=True)
    name = db.Column(db.String(32), nullable=False, name='user_name')
    password = db.Column(db.String(127), nullable=False, name='passowrd')

    def __repr__(self) -> str:
        return '<User %d>(name=%s, password=%s)' % (self.id, self.name, self.password)


if __name__ == '__main__':
    # db.create_all()

    userList = [
        # User(name='Allen', password='12345454'),
        # User(name='admin', password='12345454'),
        # User(name='superAdmin', password='12345454'),
        # User(name='tom', password='12345454'),
        # User(name='bob', password='12345454'),

    ]
    # add 插入数据
    for u in userList:
        db.session.add(u)

    db.session.commit()

    # 查询到值后直接设置属性直接commit就能保存到数据库
    # user1 = User.query.filter(User.id==1).first()
    # user1.password = 'qwererert'

    # delete 查出来的对象一定要commit
    db.session.delete(User.query.filter(User.name == 'bob'))
    db.session.commit()

    query_all = User.query.filter().all()
    print(query_all)
